// ignore_for_file: avoid_function_literals_in_foreach_calls

import 'package:flutter/cupertino.dart';
import 'package:flutter_hx/base/loading_dialog.dart';
import 'package:flutter_hx/base/utils/globalkey_utils.dart';
import 'package:flutter_hx/base/utils/toast_utils.dart';
import 'package:flutter_hx/network/HttpGo.dart';
import 'package:flutter_hx/plugs/share_plugs.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';

class ShareLogic extends GetxController {
  final brochures=<dynamic>[].obs;
  final globalKeys =<GlobalKey>[];
  final curIndex=0;
  @override
  void onInit() {
    super.onInit();
    HttpGo.instance.get("/share/brochures").then((res) {
        res.ifSuccess((data){
          brochures.value=data;
          globalKeys.clear();
          brochures.forEach((element) =>globalKeys.add(GlobalKey()));
        });
    });
  }


  Future saveShareImage()async{
    LoadingDialog.show(Get.context!);
    GlobalKeyUtils.toBytes(globalKeys[curIndex]).then((imageBytes)async{
      if(imageBytes!=null){
        await ImageGallerySaver.saveImage(imageBytes,quality: 6);
        LoadingDialog.close(Get.context!);
        ToastUtils.show("保存成功");
      }
    }).onError((error, stackTrace) {
      LoadingDialog.close(Get.context!);
    });
  }

  Future toShare()async{
    LoadingDialog.show(Get.context!);
    GlobalKeyUtils.toBytes(globalKeys[curIndex]).then((imageBytes)async{
      if(imageBytes!=null){
        final res=await ImageGallerySaver.saveImage(imageBytes,quality: 6);
        LoadingDialog.close(Get.context!);
        final filePath="${res?["filePath"]??""}";
        if(filePath.isNotEmpty) {
          SharePlugs.shareImage(url: filePath);
        }
      }else{
        LoadingDialog.close(Get.context!);
      }
    });
  }
}
